package com.example.app_translation.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.app_translation.serviceiml.DealRequestServiceImpl;
import com.example.app_translation.util.DealSQL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

@Controller
public class DealRequest {


    @Autowired
    DealRequestServiceImpl dealRequestService;

    @RequestMapping ("/getdatainfo")
    @ResponseBody
    public String getDataInfo(@RequestBody JSONObject json) {
        DealSQL dealSQL = new DealSQL();
        String code = dealRequestService.getCode(json);
        if("1".equals(code)){
            String binding = dealRequestService.getBindings(json);
            json.put("binding", binding);
            //对象api
            String api = json.getString("api");
            //drop sql 删除存在同名的表
            String drop_sql=dealSQL.getDropSql(api);
            dealRequestService.createTable(drop_sql);
            //字段的json数组
            JSONArray words = dealRequestService.getWordsBySql(json);
            //建表语句
            String create_sql=dealSQL.getCreateSql(api,words);
            //在数据库创建对应的表信息
            dealRequestService.createTable(create_sql);
            //获取数据量
            Integer count_size = dealRequestService.getSizeBySql(json);
            String datajson="";
            if(count_size>30000){
                try {
                    datajson = getDataByThread(json);
                } catch (ExecutionException | InterruptedException e ) {
                    e.printStackTrace();
                }
            }else {
                datajson=getDataByobj(json);
            }
            String insertSql = dealSQL.getInsertSql(api, words, datajson);
            dealRequestService.insertData(insertSql);
            return "ok";
        }else{
            return "fail";
        }

    }

    @GetMapping ("/getobj")
    @ResponseBody
    public String getDataByobj(@RequestBody JSONObject json){
        String binding=dealRequestService.getBindings(json);
        json.put("binding",binding);
        String objectApiName=json.getString("api");
        json.put("api",objectApiName);
        String rs = dealRequestService.getDataByApi(json);
        return rs;
    }
    @GetMapping ("/getdatabythread")
    @ResponseBody
    public String getDataByThread(@RequestBody JSONObject json) throws ExecutionException, InterruptedException {
        JSONArray rs=new JSONArray();
        String binding = dealRequestService.getBindings(json);
        json.put("binding", binding);
        String objectApiName=json.getString("api");
        Integer num = dealRequestService.getSizeBySql(json);
        Integer core=Runtime.getRuntime().availableProcessors()+2;
        String sql="select * from "+objectApiName+" where is_deleted='0'";
        int size=0;
        if(num%core>0&&num>0){
            size=num/core+1;
        }else if(num%core==0){
            size=num/core;
        }
        List<CompletableFuture<JSONArray>> reslist=new ArrayList<>();
        int cpu_num = Runtime.getRuntime().availableProcessors();
        int max=2*cpu_num;
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                core,
                max,
                2L,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(core*10),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy());
        for (int i = 0; i <core ; i++) {
            int start = i * size;
            System.out.println("线程 = " + Thread.currentThread().getName());
            String t_sql = sql + " limit " + start + "," + size;
            json.put("sql",t_sql);

            CompletableFuture.supplyAsync(
                    ()->dealRequestService.getDataBySql(json),threadPoolExecutor)
                    .whenComplete((v,t)->{
                        rs.addAll(v);
                    });
                    try {
                        TimeUnit.MICROSECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
        }
        while (threadPoolExecutor.getCompletedTaskCount()!=core) {

        }
        threadPoolExecutor.shutdown();
        System.out.println("rs.toJSONString() = " + rs.size());
        return rs.toJSONString();
    }

    @GetMapping ("/getdata")
    @ResponseBody
    public String getTest2(@RequestBody JSONObject json){
        String binding=dealRequestService.getBindings(json);
        json.put("binding",binding);
        json.put("api","Account");
        String objectApiName=json.getString("api");
        String sql="select * from "+objectApiName+" where is_deleted='0'";
        json.put("sql",sql);
        JSONArray dataBySql = dealRequestService.getDataBySql(json);
        System.out.println("dataBySql.size() = " + dataBySql.size());
        return dataBySql.toString();
    }
}
